package com.act262.vote.ui;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.swing.JOptionPane;

import com.act262.vote.bean.User;
import com.act262.vote.utils.ExcelUtils;
import com.act262.vote.utils.VoteCore;

public class VoteUi extends Frame implements ActionListener {
	private static final long serialVersionUID = 4449882311348138262L;
	TextField input;
	TextArea resultArea;
	String filePath = null;
	StringBuffer resultBuffer = new StringBuffer();

	public VoteUi() {
		this.setTitle("批量投票工具箱");
		initUI();
	}

	private void initUI() {
		this.setBounds(200, 200, 400, 400);
		this.setResizable(false);
		this.setLayout(new FlowLayout());
		initMenu();
		initControl();
		this.setVisible(true);
	}

	private void initControl() {

		/*****************************************/

		Panel selectPanel = new Panel(new GridLayout(2, 1));
		Label tip = new Label("输入投票的对象编号:      ");
		selectPanel.add(tip);

		input = new TextField();
		selectPanel.add(input);

		Button openFile = new Button("导入Excel");
		openFile.setActionCommand("export_excel");
		openFile.addActionListener(this);

		Button commit = new Button("提交");
		commit.setActionCommand("commit");
		commit.addActionListener(this);

		this.add(selectPanel);
		this.add(openFile);
		this.add(commit);

		/**********************************/
		Panel resultPanel = new Panel();
		Label resultLabel = new Label("结果");
		resultPanel.add(resultLabel, BorderLayout.NORTH);

		resultArea = new TextArea(15, 40);
		resultPanel.add(resultArea);

		this.add(resultPanel);
	}

	private void initMenu() {
		MenuBar menuBar = new MenuBar();
		MenuBarListener l = new MenuBarListener();

		Menu fileMenu = new Menu("系统");

		MenuItem exportItem = new MenuItem("导入文件");
		exportItem.setActionCommand("export_excel");
		exportItem.addActionListener(l);
		fileMenu.add(exportItem);
		fileMenu.addSeparator();

		MenuItem exitItem = new MenuItem("退出");
		exitItem.setActionCommand("exit");
		exitItem.addActionListener(l);
		fileMenu.add(exitItem);

		menuBar.add(fileMenu);
		this.setMenuBar(menuBar);

	}

	List<User> userList = null;
	List<String> numberList = null;

	private void readUser() {
		if (filePath == null) {
			JOptionPane.showMessageDialog(this, "没有指定文件", "警告!!!",
					JOptionPane.WARNING_MESSAGE);
			return;
		}
		try {
			userList = ExcelUtils.getUserListFromExcel(filePath);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private boolean checkSelectNumber(String str) {
		try {

			String regex = "^(\\d{1,2}){1}[,](\\d{1,2}[,]){0,4}(\\d{1,2}){0,1}$";

			if (str.equals("")) {
				JOptionPane.showMessageDialog(this, "输入格式不对!!");
			}
			if (str.matches(regex)) {
				numberList = Arrays.asList(str.split(","));
				return true;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		switch (e.getActionCommand()) {
		case "export_excel":
			openFileDialog();
			break;
		case "commit":
			readUser();
			if (null == userList) {
				break;
			}

			//
			if (!checkSelectNumber(input.getText().trim())) {
				JOptionPane.showMessageDialog(this, "没有选择投票对象");
				break;
			}

			// 读取数据
			for (User user : userList) {
				Thread thread = new Thread(new VoteThread(user.getName(),
						user.getPasswd()));
				thread.run();
			}
			break;

		default:
			break;
		}

	}

	private void openFileDialog() {
		FileDialog fileDialog = new FileDialog(VoteUi.this, "打开Excel文件",
				FileDialog.LOAD);
		// windows�¾�Ȼ��֧���ļ�����
		fileDialog.setFilenameFilter(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".xls") || dir.isDirectory();
			}
		});
		fileDialog.setVisible(true);
		filePath = fileDialog.getDirectory() + fileDialog.getFile();
		// ����ѡ�е�ΪExcel�ļ�
		while (!filePath.endsWith(".xls")) {
			fileDialog.setVisible(true);
		}
		System.out.println(filePath);
	}

	private final class MenuBarListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			switch (e.getActionCommand()) {

			case "exit":
				System.exit(0);
				break;

			case "export_excel":
				System.out.println("导入Excel");
				openFileDialog();
				break;

			default:
				break;
			}

		}
	}

	private final class VoteThread implements Runnable {
		String userName, userPw;

		public VoteThread(String userName, String userPw) {
			this.userName = userName;
			this.userPw = userPw;
		}

		@Override
		public void run() {
			resultBuffer.append(VoteCore.vote(userName, userPw, numberList)
					+ "\n");
			resultArea.setText(resultBuffer.toString());
			System.out.println(Thread.currentThread());
		}
	}
}
